/**
 * Copyright 2018
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.dream.inspect.modules.sys.controller;


import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dream.inspect.common.annotation.SysLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.dream.inspect.common.utils.R;
import com.dream.inspect.common.utils.StringUtil;
import com.dream.inspect.modules.app.constants.AttrConstants;
import com.dream.inspect.modules.sys.common.LoginCommon;
import com.dream.inspect.modules.sys.shiro.ShiroUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * 登录相关
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@CrossOrigin
@Controller
public class SysLoginController extends AbstractController{
    @Autowired
    private Producer producer;
    @Autowired
    private LoginCommon loginCommon;

    private static final String ATTR_CER = "javax.servlet.request.X509Certificate";
    private static final String SCHEME_HTTPS = "https";

    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public R login(String username, String password, String captcha) {
        if(!"passcode".equals(captcha)){
            String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
            if(!captcha.equalsIgnoreCase(kaptcha)){
                return R.error("验证码不正确");
            }
        }

        return loginCommon.login(username, password, AttrConstants.PKI);
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/pkilogin")
    public String pkilogin(HttpServletRequest request, HttpServletResponse res) {
        String username = "", zjhm = "", deptCode = "";
        R r = new R();
//         检测是否为https访问
        String scheme = request.getScheme();
        if (!SCHEME_HTTPS.equalsIgnoreCase(scheme)) {
            r.error("-1","不安全的请求！");
            logger.info(r.toString());
            return "redirect:pkilogin.html";
        }
        X509Certificate[] certs=(X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
        if (certs == null) {
            r.error("-1","未识别到数字证书！");
            return "redirect:pkilogin.html";
        } else {
            String dn = certs[0].getSubjectDN().toString();
            System.out.println(dn);
            Map<String, String> dnInfo = null;
            try {
                dnInfo = this.getDNInfo(dn);
            } catch (Exception e) {
                r.error("-1","非法证书！");
            }
            username = dnInfo.get("name");
            zjhm = dnInfo.get("idNum");
            deptCode = dnInfo.get("oid");
        }
        return loginCommon.pkilogin(username, zjhm, deptCode);
    }


    /**
     * PKI用到
     * @param cn
     * @return
     */
    public static Map<String,String> getDNInfo(String cn){
        Map<String,String> dnInfo = new HashMap<String,String>();
        String[] arr1 = cn.split("[,，\\s]+");
        String name = arr1[0].substring(arr1[0].indexOf("=")+1);
        String idCard = arr1[1];
        String oid =
                arr1[7].substring(arr1[7].indexOf("=")+1)
                        + arr1[6].substring(arr1[6].indexOf("=")+1)
                        + arr1[5].substring(arr1[5].indexOf("=")+1)
                        + arr1[4].substring(arr1[4].indexOf("=")+1)
                        + arr1[3].substring(arr1[3].indexOf("=")+1)
                        + arr1[2].substring(arr1[2].indexOf("=")+1)
                ;
        dnInfo.put("name", name);
        dnInfo.put("idNum", idCard);
        dnInfo.put("oid", oid);
        return dnInfo;
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }

    /**
     * 申请激活
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/sys/applyActivation")
    public R applyActivation(@RequestParam Map<String, Object> params){
        String roleId = params.get("roleId") + "";
        if(StringUtil.isEmpty(roleId)){
            return R.error("请选择需要激活的角色");
        }
        params.put("userId", getUserId());
        return loginCommon.applyActivation(params);
    }

    /**
     * 获取需要可激活的角色列表
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/sys/getRoleInfo")
    public R getRoleInfo(@RequestParam Map<String, Object> params){
        String roleId = params.get("roleId") + "";
        String roleName = params.get("roleName") + "";
        if(StringUtil.isEmpty(roleId) || StringUtil.isEmpty(roleName)){
            return R.error("角色ID或key不能为空");
        }
        return loginCommon.getRoleInfo(params);
    }

}
